/*
	网站页面控制器
*/
'use strict';
let main			= {};
var moment		= require('moment');
var fs 				= require('fs');
var AV 				= require('leanengine');
var mdCommon	= require('../modules/common');

var avAlbum 			= AV.Object.extend("Album");
var avSysConfig 	= AV.Object.extend("SysConfig");
var avNews 				= AV.Object.extend("New");
var avTrip 				= AV.Object.extend("Trip");
var avTripNote 		= AV.Object.extend("TripNote");
var avImage 			= AV.Object.extend("Image");

/**
 * 网站首页
 * 2015.04.25  by 胡斌
 */
main.homePage = function(req,res) {
	var slides=[];
	var querySysConfig 	= new AV.Query(avSysConfig);

	querySysConfig.equalTo("name","home_catagory");
	querySysConfig.first().then(function(result){
		if(typeof(result)!="undefined"){
			slides=eval('(' + result.get("value") + ')');
		}

		res.render('main/index.html',{
			user:req.AV.user,
			results:slides
		});
	},function(error) {
		mdCommon.sentErr(res,req,error,"main");
	});
}

/**
 * 网站首页
 * 2015.04.25  by 胡斌
 */
main.loginPage = function(req,res) {
	var error=req.query.error;
	res.render('main/login.html',{
		error:error,
		refer:req.query.refer,
		user:req.AV.user
	});
}

main.doLogin = function(req,res) {
	AV.User.logIn(req.body.username,req.body.password).then(function(user) {
			//console.log(user);
			//跳转到profile页面。
			if(req.body.refer)
			res.redirect(req.body.refer);
			else
			res.redirect('/my');
	},function(error) {
		if(typeof(error)=="object"){error=error.message;}
		console.error(error);
		//登录失败，跳转到登录页面
		res.redirect('/login?error='+error+"&refer="+req.body.refer);
	});
}

/**
 * 后台登录页面
 * 2015.04.18  by 胡斌
 */
main.logoutPage = function(req,res,next) {
	AV.User.logOut();
  res.redirect('/login');
}

/**
 * 网站首页
 * 2015.04.25  by 胡斌
 */
main.registerPage = function(req,res) {
	var error=req.query.error;
	res.render('main/register.html',{
		error:error,
		refer:req.query.refer,
		user:req.AV.user
	});
}

main.doRegister = function(req,res) {
	var name				= req.body.name;
	var displayname	= req.body.displayname;
	var pw1					= req.body.password;
	var pw2					= req.body.password2;
	if(pw1==pw2){
		var user = new AV.User();// 新建 AVUser 对象实例
	  user.set("username",name);// 设置用户名
	  user.set("password",pw1);// 设置密码
	  user.set('displayName',displayname);// 设置邮箱
	  user.signUp().then(function (loginedUser) {
			if(req.body.refer)
			res.redirect(req.body.refer);
			else
			res.redirect('/my');
	  }, (function (error) {
			if(typeof(error)=="object"){error=error.message;}
			res.redirect('/register?error='+error+"&refer="+req.body.refer);
	  }));
	}else{
		res.redirect('/register?error=Passwords does not match!'+"&refer="+req.body.refer);
	}
}

/**
 * 网站新闻
 * 2016.05.16  by 胡斌
 */
main.newslistPage = function(req,res) {
	var slides,pager,where=" enabled=true";
	var querySysConfig 	= new AV.Query(avSysConfig);

	querySysConfig.equalTo("name","new_banner");
	querySysConfig.first().then(function(result){
		if(typeof(result)!="undefined"){
			slides=eval('(' + result.get("value") + ')');
		}else{
			slides=[];
		}
		//console.dir(slides);
		return AV.Query.doCloudQuery('select count(*) from New where'+where);
	}).then(function(data){
		//console.dir(data);
		pager		= mdCommon.Paginate(req.query.page, req.query.pagesize, data.count);
		return AV.Query.doCloudQuery('select * from New where'+where+' limit '+(pager.currentPage-1)*pager.pagesize+','+pager.pagesize+" order by createdAt desc");
	}).then(function(data){
		res.render('main/news_list.html',{
			user:req.AV.user,
			results:data.results,
			slides:slides,
			moment:moment,
			pager:pager
		});
	},function(error) {
		mdCommon.sentErr(res,req,error,"main");
	});
}

/**
 * 获取点击数
 * 2016.08.31  by 胡斌
 */
main.doGetClicks = function(req,res) {
	var type	= req.body.type;
	var ids		= req.body.ids;
	var query;
	if(type=="image"){
		query = new AV.Query(avImage);
	}else if(type=="trip"){
		query = new AV.Query(avTrip);
	}else{
		query = new AV.Query(avNews);
	}

	query.containedIn("objectId",ids);
	query.select("objectId","clicks");
	query.find().then(function(results){
		res.json({results:results});
	},function(error) {
		mdCommon.sentErr(res,req,error,"main");
	});
}


/**
 * 文章详情页面
 * 2016.05.03  by 胡斌
 */
main.newsdetailPage = function(req, res,next) {
	//console.log("detailPage:"+req.AV.user);
	var id					= req.query.id;
	var queryNews 	= new AV.Query(avNews);
	if(!id)id="-1";

	queryNews.equalTo("objectId",id);
	queryNews.first().then(function(result) {
		if(typeof(result)=="undefined"){
			next();
		}else{
			result.increment('clicks', 1);
			result.save();
			res.render('main/news_detail.html',{
				user:req.AV.user,
				result:result,
				moment:moment
			});
		}
	},function(error) {
		next();
	});
}

/**
 * 网站新闻
 * 2016.05.16  by 胡斌
 */
main.discoverPage = function(req,res,next) {
	var tag={},pager,where=" enabled=true and isSys=false";
	var tagArr=["airline","acType","classes","flightNo","from","to"];
	for(var i=0;i<tagArr.length;i++){
		if(req.body[tagArr[i]])
		where += " and "+tagArr[i]+"='"+req.body[tagArr[i]]+"'";
	}

	var querySysConfig 	= new AV.Query(avSysConfig);
	querySysConfig.equalTo("type","tag");
	querySysConfig.find().then(function(results){
		for(var i=0;i<results.length;i++){
			tag[results[i].get("name")]=results[i].get("value").split(",");
		}
		return AV.Query.doCloudQuery('select count(*) from Image where'+where);
	}).then(function(data){
		//console.dir(data);
		pager		= mdCommon.Paginate(req.query.page, req.query.pagesize, data.count);
		return AV.Query.doCloudQuery('select * from Image where'+where+' limit '+(pager.currentPage-1)*pager.pagesize+','+pager.pagesize+" order by createdAt desc");
	}).then(function(data){
		if(req.body.ajax){
			res.json({results:data.results});
		}else{
			res.render('main/discover.html',{
				user:req.AV.user,
				results:data.results,
				moment:moment,
				pager:pager,
				query:req.body,
				tag:tag
			});
		}
	},function(error) {
		if(error==404){
			next();
		}else{
			mdCommon.sentErr(res,req,error,"main");
		}
	});
}

/**
 * 网站新闻
 * 2016.05.16  by 胡斌
 */
main.searchPage = function(req,res,next) {
	var keyword	= req.body.keyword;
	var pager,where=" enabled=true and isSys=false";
	where += " and (name like '%"+keyword+"%' or searchname like '%"+keyword.toLowerCase()+"%')";

	AV.Query.doCloudQuery('select count(*) from Image where'+where).then(function(data){
		//console.dir(data);
		pager		= mdCommon.Paginate(req.query.page, req.query.pagesize, data.count);
		return AV.Query.doCloudQuery('select * from Image where'+where+' limit '+(pager.currentPage-1)*pager.pagesize+','+pager.pagesize+" order by createdAt desc");
	}).then(function(data){
		if(req.body.ajax){
			res.json({results:data.results});
		}else{
			res.render('main/search.html',{
				user:req.AV.user,
				results:data.results,
				moment:moment,
				pager:pager,
				keyword:keyword
			});
		}
	},function(error) {
		if(error==404){
			next();
		}else{
			mdCommon.sentErr(res,req,error,"main");
		}
	});
}


/**
 * 我的图片列表
 * 2016.05.16  by 胡斌
 */
main.imageDetailPage = function(req,res,next) {
	var tag={},image;
	var querySysConfig 	= new AV.Query(avSysConfig);
	var queryImage 			= new AV.Query(avImage);
	var id							= req.query.id;

	querySysConfig.equalTo("type","tag");
	querySysConfig.find().then(function(results){
		for(var i=0;i<results.length;i++){
			tag[results[i].get("name")]=results[i].get("value");
		}
		queryImage.equalTo("objectId",id);
		queryImage.include("user");
		return queryImage.first();
	}).then(function(result){
		if(result){
			result.increment('clicks', 1);
			result.save();
			image								= result;
			var date						= result.createdAt;
			//console.dir(date);
			var queryImage1 		= new AV.Query(avImage);
			var queryImage2 		= new AV.Query(avImage);
			queryImage1.lessThan('createdAt',date);
			queryImage1.select("objectId");
			queryImage1.limit(2);
			queryImage1.descending('createdAt');
			queryImage1.notEqualTo("isSys",true);
			queryImage1.notEqualTo("enabled",false);
			queryImage2.greaterThan('createdAt',date);
			queryImage2.select("objectId");
			queryImage2.limit(2);
			queryImage2.ascending('createdAt');
			queryImage2.notEqualTo("isSys",true);
			queryImage2.notEqualTo("enabled",false);
			return AV.Promise.when(queryImage1.find(),queryImage2.find());
		}else{
			return AV.Promise.error(404);
		}
		//console.dir(tag);
	}).then(function(lessImages,greaterImages){
		//console.dir(image.get("user"));
		res.render('main/image_detail.html',{
			user:req.AV.user,
			result:image,
			tag:tag,
			lessImages:lessImages,
			greaterImages:greaterImages,
			moment:moment
		});
	},function(error) {
		if(error==404){
			next();
		}else{
			mdCommon.sentErr(res,req,error,"main");
		}
	});
}


/**
 * 游迹列表
 * 2016.05.16  by 胡斌
 */
main.triplistPage = function(req,res) {
	var pager,where=" enabled=true and cover is exists";
	AV.Query.doCloudQuery('select count(*) from Trip where'+where).then(function(data){
		//console.dir(data);
		pager		= mdCommon.Paginate(req.query.page, req.query.pagesize, data.count);
		return AV.Query.doCloudQuery('select include user,* from Trip where'+where+' limit '+(pager.currentPage-1)*pager.pagesize+','+pager.pagesize+" order by createdAt desc");
	}).then(function(data){
		res.render('main/trip_list.html',{
			user:req.AV.user,
			results:data.results,
			moment:moment,
			pager:pager
		});
	},function(error) {
		mdCommon.sentErr(res,req,error,"main");
	});
}

/**
 * 游迹详情页面
 * 2016.05.03  by 胡斌
 */
main.tripdetailPage = function(req, res,next) {
	var trip,tripNoteArr=[];
	var id					= req.query.id;
	var queryTrip 	= new AV.Query(avTrip);
	if(!id)id="-1";

	queryTrip.equalTo("objectId",id);
	queryTrip.include("user");
	queryTrip.first().then(function(result) {
		//console.log(result);
		if(typeof(result)=="undefined"){
			next();
		}else{
			result.increment('clicks', 1);
			result.save();
			trip								= result;
			var queryTripNote 	= new AV.Query(avTripNote);
			queryTripNote.equalTo("trip",trip);
			queryTripNote.ascending('sort');
			queryTripNote.find().then(function(results) {
				for(var i=0;i<results.length;i++){
					var tripNote={};
					if(results[i].get("image")){
						tripNote.id=results[i].id;
						tripNote.img=results[i].get("image").id;
						tripNote.text=results[i].get("text");
						tripNoteArr.push(tripNote);
					}
				}

				//console.dir(tripNoteArr);
				//console.dir(images);
				res.render('main/trip_detail.html',{
					user:req.AV.user,
					result:trip,
					moment:moment,
					tripNoteArr:tripNoteArr
				});
			},function(error) {
				console.log(error);
				next();
			});
		}
	},function(error) {
		next();
	});
}


/**
 * 列表页面
 * 2015.06.02  by 胡斌
 */
main.commentListPage = function(req, res) {
	var pager,where	= " objectId is exists";
	var id					= req.query.id?req.query.id:req.body.id;
	var type				= req.query.type?req.query.type:req.body.type;
	var ajax				= req.query.ajax?req.query.ajax:req.body.ajax;
	//console.dir(req.query);
	//console.dir(req.body);
	if(typeof(type)==undefined){
		where	+= " and toUser =pointer('_User','"+id+"')";
	}else if(type=="new"){
		where	+= " and type='new' and new =pointer('New','"+id+"')";
	}else if(type=="new"){
		where	+= " and type='trip' and trip =pointer('Trip','"+id+"')";
	}else{
		where	+= " and type='image' and image =pointer('Image','"+id+"')";
	}

	AV.Query.doCloudQuery('select count(*) from Comment where'+where).then(function(data){
		pager		= mdCommon.Paginate(req.query.page, req.query.pagesize, data.count);
		return AV.Query.doCloudQuery('select include toUser,include fromUser,* from Comment where'+where+' limit '+(pager.currentPage-1)*pager.pagesize+','+pager.pagesize);
	}).then(function(data) {
		if(ajax){
			res.render('main/ajax-comment-list.html',{
				results:data.results,
				moment:moment,
				pager:pager
			});
		}else{
			res.render('main/comment-list.html',{
				user:req.AV.user,
				results:data.results,
				moment:moment,
				pager:pager
			});
		}
	},function(error) {
		mdCommon.sentErr(res,req,error,"main");
	});
}

/**
 * 静态页面
 * 2015.04.20  by 胡斌
 */
main.htmlPage = function(req,res) {
	var path	= req.path.split("/");
	var fn		= path[path.length-1];
	var type	= fn.split(".");
	display(res,type[0],{res:res});
}

module.exports = main;
